﻿using Microsoft.AspNetCore.Mvc;
using RankingWorld.Models;
using RankingWorld.Repositories;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RankingWorld.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RankingsController : ControllerBase
    {
        private readonly IRankingRepository _rankingRepository;

        public RankingsController(IRankingRepository rankingRepository)
        {
            _rankingRepository = rankingRepository;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<Ranking>>> GetAllRankings()
        {
            var rankings = await _rankingRepository.GetAllRankingsAsync();
            return Ok(rankings);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Ranking>> GetRankingById(int id)
        {
            var ranking = await _rankingRepository.GetRankingByIdAsync(id);
            if (ranking == null)
            {
                return NotFound();
            }
            return Ok(ranking);
        }

        [HttpPost]
        public async Task<ActionResult<int>> AddRanking(Ranking ranking)
        {
            var id = await _rankingRepository.AddRankingAsync(ranking);
            return CreatedAtAction(nameof(GetRankingById), new { id = id }, id);
        }

        [HttpPut("{id}")]
        public async Task<ActionResult<int>> UpdateRanking(int id, Ranking ranking)
        {
            if (id != ranking.Id)
            {
                return BadRequest();
            }
            var result = await _rankingRepository.UpdateRankingAsync(ranking);
            return Ok(result);
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult<int>> DeleteRanking(int id)
        {
            var result = await _rankingRepository.DeleteRankingAsync(id);
            return Ok(result);
        }
    }
}